﻿using System;
using System.ComponentModel;
using System.Web.UI;
using System.Collections;
using System.Collections.Generic;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.Core;
using System.Web;

namespace Yuanlin.Business
{
    public class VisitInfo : YuanlinUserControl
    {
        protected Literal ltlUserName;
        protected Literal ltlCompanyName;
        protected Literal ltlNikeName;
        protected Literal ltlVisitTodayNum;
        protected Literal ltlTotalNum;
        protected Literal ltlLastDateTime;
        protected Literal ltlLogin;
        protected HtmlControl lastDateDiv;
        private YuanlinUser user;
        private YuanlinUser loginUser = HttpContext.Current.User as YuanlinUser;
        private string tradeType = UrlManager.Instance.GetParameterValue<string>(YuanlinParameterName.TradeType);
        private int entityId = UrlManager.Instance.GetParameterValue<int>(YuanlinParameterName.VisitCompanyId);
        private int categoryId = UrlManager.Instance.GetParameterValue<int>(YuanlinParameterName.CategoryId);
        private string greenNum = UrlManager.Instance.GetParameterValue<string>(YuanlinParameterName.GreenNum);

        public int TradeType
        {
            get
            {
                int i = -1;
                switch (tradeType)
                {
                    case "0":
                        i = 1;
                        break;
                    case "1":
                        i = 1;
                        break;
                    case "2":
                        i = 2;
                        break;
                    case "3":
                        i = 3;
                        break;
                    default:
                        break;
                }
                return i;
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                user = UserManager.GetUser(UserIdFromGreenNum) as YuanlinUser;
                if (user == null)
                {
                    return;
                }
                ltlUserName.Text = user.RegisterGreenNumber.Value;;
                ltlCompanyName.Text = user.CompanyName.Value;
                ltlNikeName.Text = user.NickName.Value;

                IsLogin();
                UpdateData();
                BindData();
                RecordVisitorInfo();
            }
        }

        private Guid GetCompanyMemberId()
        {
            if (!string.IsNullOrEmpty(greenNum))
            {
                Member member = MemberManager.GetMember(greenNum);
                if (member != null)
                {
                    return member.MemberId;
                }
            }
            return Guid.Empty;
        }

        /// <summary>
        /// 当前访问的公司是否在线
        /// </summary>
        private void IsLogin()
        {
            if (OnlineMemberManager.Instance.IsMemberOnline(GetCompanyMemberId()))
            {
                ltlLogin.Text = "在线";
            }
            else
            {
                ltlLogin.Text = "离线";
            }
        }
        /// <summary>
        /// 更新本企业的访问信息
        /// </summary>
        private void UpdateData()
        {
            if (loginUser.IsAnonymous)
            {
                AnonymousVisit();
                return;
            }

            CompanyVisit();
        }

        #region 更新访问绿商号的表

        private EntityList CompanyVisitEntityList()
        {
            //更新本公司的总访问量（同一个用户一天访问本公司多次时，也只算一次）
            VisitCompanyListRequest request = new VisitCompanyListRequest();
            request.UserId = UserIdFromGreenNum;
            request.VisitUserId = loginUser.EntityId.Value;
            request.CategoryId = categoryId;
            request.TradeType = tradeType == null ? "-1" : tradeType;
            request.PageIndex = 0;
            request.PageSize = int.MaxValue;
            request.LastDate = Globals.ChangeType<DateTime>(DateTime.Now.ToShortDateString());
            return BusinessManager.GetVisitCompanyList(RequestHelper.BuildGetVisitCompanyListRequest(request));
        }
        /// <summary>
        /// 更新访问绿商号的表
        /// </summary>
        private void CompanyVisit()
        {
            EntityList visitCompanys = CompanyVisitEntityList();
            if (visitCompanys.Count== 0)
            {
                user.TotalVisitCount.Value++;
                UserManager.UpdateUser(user);
            }
            VisitCompany visitCompany = null;
            if (visitCompanys.Count == 0)//首次访问，新增
            {
                visitCompany = new VisitCompany();
                visitCompany.UserId.Value = UserIdFromGreenNum;
                visitCompany.VisitUserId.Value = loginUser.EntityId.Value;
                visitCompany.VisitGreenNumber.Value = loginUser.CurrentGreenNumber;
                visitCompany.ProductId.Value = entityId;
                visitCompany.CategoryId.Value = categoryId;
                visitCompany.TradeType.Value = tradeType == null ? "-1" : tradeType;
                visitCompany.Num.Value++;
                visitCompany.LastDate.Value = DateTime.Parse(DateTime.Now.ToShortDateString());
                BusinessManager.CreateVisitCompany(visitCompany);
            }
            else//非首次访问，更新
            {
                visitCompany = visitCompanys[0] as VisitCompany;
                visitCompany.LastDate.Value = DateTime.Parse(DateTime.Now.ToShortDateString());
                BusinessManager.UpdateVisitCompany(visitCompany);
            }
        }

        #endregion

        #region 匿名更新表

        private string GetCity()
        {
            string ipStr = IpClass.GetIp();
            if (ipStr.Length == 0)
            {
                return "";
            }

            string city = IpClass.GetAddressWithIP(ipStr);
            int i = city.IndexOf("市");
            if (i > -1 && i < city.Length)
            {
                city = city.Substring(0, i);
            }
            return city;
        }
        private EntityList AnonymousVisitEntityList(string city)
        {
            //更新本公司的总访问量（同一个用户一天访问本公司多次时，也只算一次）
            AnonymousVisitCompanyListRequest request = new AnonymousVisitCompanyListRequest();
            request.City = city;
            request.UserId = UserIdFromGreenNum;
            request.TradeType = tradeType == null ? "-1" : tradeType;
            request.CategoryId = categoryId;
            request.PageIndex = 0;
            request.PageSize = int.MaxValue;
            request.LastDate = Globals.ChangeType<DateTime>(DateTime.Now.ToShortDateString());
            return BusinessManager.GetAnonymousVisitCompanyList(RequestHelper.BuildGetAnonymousVisitCompanyListRequest(request));
            
        }
        /// <summary>
        /// 对匿名访问的处理
        /// </summary>
        private void AnonymousVisit()
        {
            string city = GetCity();
            if (string.IsNullOrEmpty(city))
            {
                return;
            }
            EntityList anonys = AnonymousVisitEntityList(city);
            if (anonys.Count == 0)
            {
                user.TotalVisitCount.Value++;
                UserManager.UpdateUser(user);
            }
            AnonymousVisitCompany anony = null;
            if (anonys.Count==0)//以前没有过，新增
            {
                anony = new AnonymousVisitCompany();
                anony.UserId.Value = UserIdFromGreenNum;
                anony.City.Value = city;
                anony.ProductId.Value = entityId;
                anony.CategoryId.Value = categoryId;
                anony.TradeType.Value = tradeType == null ? "-1" : tradeType;
                anony.Num.Value++;
                anony.LastDate.Value = DateTime.Parse(DateTime.Now.ToShortDateString());
                BusinessManager.CreateAnonymousVisitCompany(anony);
            }
            else//之前访问过，更新
            {
                anony = anonys[0] as AnonymousVisitCompany;
                anony.LastDate.Value = DateTime.Parse(DateTime.Now.ToShortDateString());
                BusinessManager.UpdateAnonymousVisitCompany(anony);
            }

        }

        #endregion

        private void BindData()
        {
            //总访问量
            ltlTotalNum.Text = user.TotalVisitCount.ToString();
            if (loginUser.IsAnonymous || loginUser.EntityId.Value != UserIdFromGreenNum)
            {
                lastDateDiv.Visible = false;
            }
            else
            {//只有本公司登陆的才显示上次访问时间
                ltlLastDateTime.Text = user.LastLoginDate.Value.ToString("yyyy-MM-dd HH:mm");
            }
            //今日访问量=（今日匿名+今日绿商用户）访问
            string city = GetCity();
            int anonyCount = 0;
            if (!string.IsNullOrEmpty(city))
            {
                anonyCount = AnonymousVisitEntityList(city).Count;
            }
            ltlVisitTodayNum.Text = (CompanyVisitEntityList().Count + anonyCount).ToString();
        }
        //记录来访者信息
        private void RecordVisitorInfo()
        {
            CompanyVisitorInfo companyVisitorInfo = new CompanyVisitorInfo();
            if (user.IsAnonymous)
            {
                companyVisitorInfo.Visitor.Value = IpClass.GetIp();//访问者 ip或注册的绿商号
            }
            else
            {
                companyVisitorInfo.Visitor.Value = loginUser.RegisterGreenNumber.Value;
            }
            YuanlinUser company = UserManager.GetUser(UserIdFromGreenNum) as YuanlinUser;//被访问的公司
            if (company == null)
            {
                return;
            }

            EntityList companyVisitorInfos = BusinessManager.GetCompanyVisitorInfoList(RequestHelper.BuildGetCompanyVisitorInfoListRequest(companyVisitorInfo.Visitor.Value, company.EntityId.Value,0,1));
            if (companyVisitorInfos.Count == 0)//此来访者首次访问本公司
            {
                companyVisitorInfo.UserId.Value = company.EntityId.Value;
                companyVisitorInfo.CompanyName.Value = company.CompanyName.Value;
                companyVisitorInfo.GreenNumber.Value = company.RegisterGreenNumber.Value;
                companyVisitorInfo.CompanyScale.Value = company.CompanyScale.Value;
                companyVisitorInfo.CompanyAddress.Value = company.CompanyAddress.Value;
                companyVisitorInfo.CompanyContactPhone.Value = company.CompanyContactPhone.Value;
                companyVisitorInfo.CompanyFixedTelephone1.Value = company.CompanyFixedTelephone1.Value;
                companyVisitorInfo.CompanyFixedTelephone2.Value = company.CompanyFixedTelephone2.Value;
                companyVisitorInfo.CreateDate.Value = DateTime.Now;

                BusinessManager.CreateCompanyVisitorInfo(companyVisitorInfo);
            }
            else//非首次访问的就更新访问日期
            { 
                companyVisitorInfo = companyVisitorInfos[0] as CompanyVisitorInfo;
                companyVisitorInfo.CreateDate.Value = DateTime.Now;
                BusinessManager.UpdateCompanyVisitorInfo(companyVisitorInfo);
            }
        }
    }
}
